package com.zsguan.z.meixi;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import com.zsguan.z.slogger4andr.ZLogger;

import java.io.IOException;
import java.io.InputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

/**
 * Created by chshqiang on 15-9-12.
 * Test Activity
 */
public class ZTestActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        testClassGetResourceAsStream();

        testGetBoundry();
    }

    private void testGetBoundry() {
        ZLogger.i(getBoundry());
    }

    public void testClassGetResourceAsStream() {
        try {
            ZLogger.i(getCertificate(ZTestActivity.this, "server.cer").toString());
        } catch (CertificateException | IOException e) {
            ZLogger.e("CertificateException | IOException");
            e.printStackTrace();
        }
    }

    // 根据当前时间得到一组随机数字字母组合
    private static String getBoundry() {
        StringBuilder sb = new StringBuilder();

        for (int t = 1; t < 12; ++t) {
            long time = System.currentTimeMillis() + (long) t;
            if (time % 3L == 0L) {
                sb.append((char) ((int) time) % 9);
            } else if (time % 3L == 1L) {
                sb.append((char) ((int) (65L + time % 26L)));
            } else {
                sb.append((char) ((int) (97L + time % 26L)));
            }
        }

        return sb.toString();
    }

    private static Certificate getCertificate(Context context, String name) throws CertificateException, IOException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        InputStream certInput = ZTestActivity.class.getResourceAsStream(name);

        if (null == certInput) {
            ZLogger.e("Certificate input is null");
            certInput = context.getAssets().open(name);
        }

        Certificate certificate;
        try {
            certificate = cf.generateCertificate(certInput);
        } finally {
            certInput.close();

        }

        return certificate;
    }

}
